/**
 * SceneTitle
 * 	@brief  Shows the main screen of the game
 * 	@author Bruno Miguel de Oliveira Tamer <bmotamer@gmail.com>
 */

using UnityEngine;

public class SceneTitle : MonoBehaviour
{
	
	public  Texture2D Background;
	public  Texture2D Fog;
	public  Texture2D Title;
	public  float 	  FogSpeed;
	public  float 	  FadeInSpeed;
	public  float 	  FadeOutSpeed;
	public  float 	  TitleFadeInSpeed;
	public  float 	  TitleZoomInSpeed;
	private byte      _Step;
	private float     _Alpha;
	private float     _TitleAlpha;
	private float     _TitleZoom = 1.0f;
	private int       _FogOffset;
	private string    _NextLevel;
	
	public void Update()
	{
		float smoothDeltaTime = Mathf.Clamp(Time.smoothDeltaTime, 0.01666667f, float.MaxValue);
		if (Fog)
			_FogOffset = Mathf.RoundToInt((_FogOffset + FogSpeed * smoothDeltaTime) % Fog.width);
		switch (_Step)
		{
		case 0:
			_Alpha = Mathf.Clamp(_Alpha + FadeInSpeed * smoothDeltaTime, 0.0f, 1.0f);
			if (_Alpha == 1.0f)
				++_Step;
			break;
		case 1:
			_TitleAlpha = Mathf.Clamp(_TitleAlpha + TitleFadeInSpeed * smoothDeltaTime, 0.0f, 1.0f);
			_TitleZoom  = Mathf.Clamp(_TitleZoom - TitleZoomInSpeed * smoothDeltaTime, 0.75f, float.MaxValue);
			if ((_TitleAlpha == 1.0f) && (_TitleZoom == 0.75f))
				++_Step;
			break;
		case 3:
			_Alpha       = Mathf.Clamp(_Alpha - FadeOutSpeed * smoothDeltaTime, 0.0f, 1.0f);
			audio.volume = 0.75f * _Alpha;
			if (_Alpha == 0.0f)
				++_Step;
			break;
		case 4:
			if (string.IsNullOrEmpty(_NextLevel))
				Application.Quit();
			else
				Application.LoadLevel(_NextLevel);
			break;
		}
	}
	
	public void OnGUI()
	{
		Matrix4x4 tempMatrix = GUI.matrix;
		Color     tempColor  = GUI.color;
		GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(Screen.width / 1024.0f, Screen.height / 512.0f, 1.0f));
		GUI.color  = Color.white * _Alpha;
		if (Background)
			GUI.DrawTexture(
				new Rect(0.0f, 0.0f, Background.width, Background.height),
				Background
			);
		GUI.color = Color.white * _Alpha * 0.25f;
		if (Fog)
			GUI.DrawTextureWithTexCoords(
				new Rect(0.0f, 0.0f, Fog.width, Fog.height),
				Fog,
				new Rect((float)_FogOffset / Fog.width, 0.0f, 1.0f, 1.0f)
			);
		GUI.color  = Color.white * _Alpha * _TitleAlpha;
		if ((_Step > 0) && Title)
		{
			float factor = 1.0f / (_TitleZoom + 0.25f);
			GUI.DrawTexture(
				new Rect(160.0f * factor, 64.0f * factor, _TitleZoom * Title.width, _TitleZoom * Title.height),
				Title
			);
		}
		if (_Step == 2)
		{
			bool pressedStart = GUI.Button(new Rect(0.5f * (160.0f + Title.width - 128.0f), 320.0f, 128.0f, 32.0f), "Play") || Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter);
			bool pressedExit  = GUI.Button(new Rect(0.5f * (160.0f + Title.width - 128.0f), 384.0f, 128.0f, 32.0f), "Exit") || Input.GetKeyDown(KeyCode.Escape);
			if (pressedStart)
				_NextLevel = "SceneGame";
			if (pressedStart || pressedExit)
				_Step = 3;
		}
		GUI.matrix = tempMatrix;
		GUI.color  = tempColor;
	}
	
}